package com.yzzrjy.util;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ResponseUtils {
    public static final int SUCCESS_CODE = 0;
    public static final int PARAMETER_ERROR_CODE = 900; //参数错误
    public static final int NOT_FIND_CODE = 901; //未找到资源
    public static final int USER_NOT_EXIST_CODE = 902; //用户不存
    public static final int USER_SIGN_ERROR_CODE = 903; //用户签名错误
    public static final int SYSTEM_BUSY = 904; //用户签名错误

    public static final int OTHER_ERROR = 905; //其他错误

    private static String responseString(int code, String msg, Object data){
        JSONObject responseObj = new JSONObject();
        responseObj.put("code", code);
        responseObj.put("msg", msg);
        responseObj.put("data", data);
        return responseObj.toJSONString();
    }

    public static void parameterError(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.getWriter().println(responseString(PARAMETER_ERROR_CODE, "参数异常", null));
    }

    public static void notFindError(HttpServletResponse response, String error) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.getWriter().println(responseString(NOT_FIND_CODE, error, null));
    }

    public static void otherError(HttpServletResponse response, String error) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.getWriter().println(responseString(OTHER_ERROR, error, null));
    }

    public static void userNotExist(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.getWriter().println(responseString(USER_NOT_EXIST_CODE, "用户不存在", null));
    }

    public static void userSignError(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.getWriter().println(responseString(USER_SIGN_ERROR_CODE, "签名错误或过期请重新登录", null));
    }

    public static void systemBusy(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.getWriter().println(responseString(SYSTEM_BUSY, "系统繁忙", null));
    }

    public static void success(HttpServletResponse response, Object jsonData) throws IOException {
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        response.getWriter().println(responseString(SUCCESS_CODE, "", jsonData));
    }

}
